package util;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import lombok.SneakyThrows;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MillionSecondsDateDeserializer implements ObjectDeserializer {
    public final static MillionSecondsDateDeserializer instance = new MillionSecondsDateDeserializer();

    @SneakyThrows
	@Override
    public Date deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        JSONLexer lexer = parser.lexer;
        if (lexer.token() == JSONToken.LITERAL_INT) {
            String val = lexer.numberString();
            lexer.nextToken(JSONToken.COMMA);

            try {
                long timeInMillis = Long.parseLong(val);
                return new Date(timeInMillis);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Error parsing date: " + val, e);
            }
        } else if (lexer.token() == JSONToken.LITERAL_STRING) {
            String val = lexer.stringVal();
            lexer.nextToken(JSONToken.COMMA);

            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                return dateFormat.parse(val);
            } catch (ParseException e) {
				dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
				return dateFormat.parse(val);
            }
        } else {
            throw new IllegalArgumentException("Expecting an int or string, but got " + lexer.token());
        }
    }

    @Override
    public int getFastMatchToken() {
        return JSONToken.LITERAL_INT;
    }
}